﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;
using AG.Utilities;

namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class DatabaseCheckDatabaseSnapshots : IssueTypeCheckBase
    {
        public DatabaseCheckDatabaseSnapshots()
        {
            IssueTypeId = 3019;
        }

        public override void Check()
        {
            try
            {
               
                HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);
                Issue issue;

                ThresholdValue numberOfSnapshotsPerDatabase = dc.ThresholdValues.FirstOrDefault(t => t.IssueTypeID == IssueTypeId && t.ThresholdValueID == 1);
                ThresholdValue hoursAgo = dc.ThresholdValues.FirstOrDefault(t => t.IssueTypeID == IssueTypeId && t.ThresholdValueID == 2);
               
                var qry = (from i in dc.Databases
                           from s in i.Databases
                           where i.DatabaseID == s.SourceDatabaseId && s.CreateDate < (DateTime.Now.Date.AddHours((int)(-hoursAgo.Value)))
                           && 0 < (from sc in dc.Databases where s.SourceDatabaseId == sc.SourceDatabaseId group sc by sc.SourceDatabaseId into g select g.Count()).First()
                           select i).Distinct();
                foreach (var snapshot in qry)
                {
                 

                    issue = new Issue();

                    //Get Issuetype object  And Create a new  Global issue object 
                    IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                    issue.IssueType = issueType;
                    issue.TargetId = snapshot.DatabaseID;
                    issue.Description = issueType.Description.Replace("{Database}", snapshot.DatabaseName);

                    dc.Issues.InsertOnSubmit(issue);
                }

                dc.SubmitChanges();

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }



    }
}
